#!/usr/bin/Rscript

outfile = 'arcata-rsl-daily-ppt-inch.formatted.txt'
path = "raw/"
files = system(paste('ls',path), intern=T)
files = paste(path,files,sep='')


for(i in 1:length(files)){

        #get the starting year (which I changed in each of the files to 4 digit yearsi)
    sYear = as.integer(scan(files[i],skip=3,nlines=1,what = 'character',quiet=T)[2])
    #cat(sYear,"\n")

        #read in the data for this year
    tmp = as.matrix(read.table(files[i],fill=T,header=F, skip=6)) 

        #explicitly get the years for a cbind
    yearVec = vector('integer',nrow(tmp))
    for(j in 1:nrow(tmp)){
        if(tmp[j,1] <= 12){
            yearVec[j] = sYear
        }else{
            yearVec[j] = sYear + 1
        }
    }
        
        #stick on the years 
    tmp = cbind(yearVec,tmp)
    
    if(i==1) data = tmp
    else data = rbind(data,tmp)
    
}

write(t(data[!is.na(data[,4]),1:4]),file = outfile,ncolumns = 4)
cat('wrote',outfile,'\n')

